import sqliteGroupMembers from "@/sqlite_services/group_members.js";
import groupMembersApi from "@/services/api/group_members.js";
let pendingRequests = {}; //队列避免重复请求
export default {
	state: {
		group_id:0,
		groupMemberInfo: {}
	},
	mutations: {
		//设置该群的信息
		setGroupMemberInfo(state, { groupId, data }) {
			state.group_id = groupId
			state.groupMemberInfo = data.reduce((acc, user) => {
			  acc[user.user_id] = user;
			  return acc;
			}, {});
		},
		//群管理接口时调用
		setArrayManagerInfo(state,data){
			if(data.groupId == state.group_id){
				for (const userId in state.groupMemberInfo) {
					Vue.set(state.groupMemberInfo[userId], 'role', 'member');
				}
				data.data.forEach(member => {
					Vue.set(state.groupMemberInfo, member.user_id, member);
				});
			}
		},
		setArrayMemberInfo(state,data){
			if(data.groupId == state.group_id){
				data.data.forEach(member => {
					Vue.set(state.groupMemberInfo, member.user_id, member);
				});
			}
		},
		//更新聊天中群的成员-验证当前聊天
		updateGroupMembersInfo(state, { group_id, data ,noVerify }) {
		  //如果没有开启不验证,则需要验证group_id
		  if (!noVerify && group_id != state.group_id)return
		  if (Array.isArray(data)) {
		    // 批量更新
		    data.forEach(updatedMember => {
		      if (state.groupMemberInfo[updatedMember.user_id]) {
		        for (let key in updatedMember) {
		          if (updatedMember[key] != state.groupMemberInfo[updatedMember.user_id][key]) {
		            Vue.set(state.groupMemberInfo[updatedMember.user_id], key, updatedMember[key]);
		          }
		        }
		      }
		    });
		  } else {
		    // 单个更新
		    if (state.groupMemberInfo[data.user_id]) {
		      for (let key in data) {
		        if (data[key] != state.groupMemberInfo[data.user_id][key]) {
		          Vue.set(state.groupMemberInfo[data.user_id], key, data[key]);
		        }
		      }
		    }
		  }
		},
		//离开这个页面清楚
		delGroupMemberInfo(state, groupId) {
			if(groupId == state.group_id){
				state.group_id = 0
				state.groupMemberInfo = {}
				pendingRequests = {}
			}
		},
	},
	actions: {
		//获取数据库所有的群成员
		async getSqlGroupMemberInfo({commit,state}, groupId){
			let data = []
			try{
				let infos = await sqliteGroupMembers.getGroupMembersList(groupId)
				if(infos)data = infos
			}catch(e){
				//TODO handle the exception
			}
			commit('setGroupMemberInfo',{
				groupId,
				data
			})
		},
		//请求查询群成员
		async fetchGroupUserInfo({dispatch,state}, {groupId,userId}) {
			if(groupId != state.group_id)return
			if (state.groupMemberInfo[userId]) {
				return state.groupMemberInfo[userId]
			}
			
			// 检查是否已有相同 userId groupId 的请求正在进行
			if (pendingRequests[userId + '' + groupId]) {
				return pendingRequests[userId + '' + groupId]
			}
			// 创建一个新的承诺用于存储请求结果
			const memberInfoPromise = (async () => {
				try {
					const userInfoFromAPI = await groupMembersApi.getGroupMemberInfo({
						group_id:groupId,
						members:[userId]
					});
					return userInfoFromAPI;
				} finally {
					delete pendingRequests[userId + '' + groupId];
				}
			})();
			// 将该请求的承诺存储到 pendingRequests 中
		    pendingRequests[userId + '' + groupId] = memberInfoPromise;
			// 获取到结果后选择所需的字段
		    return memberInfoPromise
		}
	}
};